<template>
  <div class="app-container">
    <el-form :model="queryParamsInit" ref="queryFormInit" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="数据库类型" prop="dataBaseType">
        <el-select @change="changeDataBaseType($event)" filterable clearable v-model="queryParamsInit.dataBaseType" placeholder="请选择数据库类型">
          <el-option
            v-for="dict in dict.type.report_database_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
        <span slot="label">
            <el-tooltip content="用于导出的时候选择对应数据库类型的数据" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            数据库类型
        </span>
      </el-form-item>
      <el-form-item label="版本号" prop="hisVersion">
        <el-select @change="changeHisVersion($event)"  clearable filterable  v-model="queryParamsInit.hisVersion" placeholder="请选择版本号">
          <el-option
            v-for="dict in hisVersions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
        <span slot="label">
            <el-tooltip content="用于导出的时候选择对应版本的数据，或者按照版本读取文件" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            版本号
        </span>
      </el-form-item>
      <el-form-item label="所属客户" prop="customerId">
        <treeselect style="width: 300px;" v-model="queryParams.customerId" :show-count="true"
                    :multiple="false"
                    :disable-branch-nodes="true"
                    @keyup.enter.native="handleQuery"
                    :options="customerTree"  placeholder="请输入所属客户" />
        <span slot="label">
            <el-tooltip content="用于导出的时候相同业务主键的数据，优选取对应客户的数据" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            所属客户
        </span>
      </el-form-item>
    </el-form>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
     <!-- <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reportworld:kettle:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="readExecl"
          v-hasPermi="['reportworld:kettle:readExecl']"
        >读取ETL文件</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="border" max-height="550px" v-loading="loading" :data="taskList"
              @selection-change="handleSelectionChange" @row-click="rowClick"
              @sort-change="handleSortChange" :row-style="tableRowStyle" ref="task"
             >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column  type="index" min-width="5%"  label="编号"> </el-table-column>
      <el-table-column label="任务名称" align="center" width="400" prop="taskName" :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="备注" width="300" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="排序" width="180" align="center" prop="orderNum" :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['descending', 'ascending']"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog v-if="upload.open" :title="upload.title" :close-on-click-modal ="false" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .XLSX"
        :headers="upload.headers"
        :action="upload.url + '?hisVersion=' + this.queryParamsInit.hisVersion"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
        <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 生成SQL(不直接到脚本提交页面)
        </div>
          <span>仅允许导入xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="openScript"  :close-on-click-modal ="false"  :title="titleScript" @ :visible.sync="openScript" width="1300px" append-to-body>
      <scriptInfo :scriptSqlInfo="scriptSqlInfo" :hisVersion="hisVersion" ref="child"> </scriptInfo >
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileFormChild">确 定</el-button>
        <el-button @click="openScript = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listTask,init} from "@/api/reportworld/kettle";
  import {getTableRowStyle} from "@/utils/yss";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import scriptInfo from "@/views/reportworld/script/info";

  export default {
    name: "Task",
    components: {
      Treeselect,
      scriptInfo
    },
    dicts: ['report_database_type','report_version'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        taskNames:[],
        execlName:"",
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 采集任务表格数据
        taskList: [],
        // 弹出框
        titleScript: "",
        openScript:false,
        hisVersion:'',
        scriptSql:'',
        hisVersions:[],
        // 所属客户
        customerTree: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          id: null
        },
        queryParamsInit:{
          dataBaseType:'ORACLE',
          hisVersion:null
        },
        // 导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/reportworld/kettle/readExecl",
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: { }
      };
    },
    created() {
      this.init();
    },
    methods: {
      changeHisVersion(value){
        this.queryParamsInit.hisVersion=value;
        this.getList();
      },
      changeDataBaseType(value){
        this.queryParamsInit.dataBaseType=value;
        this.getList();
      },
      /** 查询采集任务列表 */
      getList() {
        this.loading = true;
        this.taskList = [];
        this.queryParams.dataBaseType=this.queryParamsInit.dataBaseType;
        this.queryParams.hisVersion=this.queryParamsInit.hisVersion;
        listTask(this.queryParams).then(response=> {
          this.taskList = response.rows;
         this.total = response.total;
         this.loading = false;
      }) ;
      },
      init(){  // 导出版本选择
        init().then(response => {
          this.hisVersions = response.hisVersions;
          this.customerTree=response.customerTree;
          this.loading = false;
          this.getList();
      });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.taskNames = selection.map(item => item.taskName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },
      /** 导出按钮操作 */
      handleExport() {
        if(this.queryParams.hisVersion){
          this.execlName="采集任务_"+this.queryParams.hisVersion;
        }else{
          this.execlName="采集任务_"+this.dict.type.report_version[0].value;
        }
        if(this.ids.length == 1){
          if(this.queryParams.hisVersion){
            this.execlName= this.taskNames[0] +"_"+ this.queryParams.hisVersion;
          }else{
            this.execlName= this.taskNames[0] +"_"+ this.dict.type.report_version[0].value;
          }
        }
        this.queryParams.ids= this.ids;
        this.queryParams.dataBaseType=this.queryParamsInit.dataBaseType;
        this.download('reportworld/kettle/downKettleExecl', {
          ...this.queryParams
      },
        `${this.execlName}_${new Date().getTime()}.xlsx`
      )
      },
      tableRowStyle({row, rowIndex}) {
        return getTableRowStyle(row,rowIndex,this.ids);
      },
      /** 单击选中行数据 */
      rowClick(row) {
        this.$refs.task.toggleRowSelection(row);
      },
      readExecl(){
        if(this.queryParamsInit.hisVersion){
          this.upload.title = "读取ETL文件";
          this.upload.open = true;
          this.$modal.confirm('是否确认读取'+this.queryParamsInit.hisVersion+'版本生成脚本吗？').then(function() {
            return;
          }).then(() => {
          }).catch(() => {this.upload.open = false;});
        }else{
          this.upload.title = "读取ETL文件";
          this.upload.open = true;
        }
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(200 != response.code){
          this.$modal.msgError(response.msg);
          return;
        }
        if(this.upload.updateSupport){
          this.download('reportworld/kettle/handleDownSql', {}, `ETL_${new Date().getTime()}.sql`)
        }else{
          //打开提交脚本页面
          this.openScript =true;
          this.scriptSqlInfo = response.msg;
          if(this.queryParams.hisVersion){
            this.hisVersion=this.queryParams.hisVersion;
          }else{
            this.hisVersion=this.dict.type.report_version[0].value;
          }
          this.titleScript = "脚本详细信息";
        }
      },
      submitFileFormChild() {
        this.$refs.child.submitForm();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>
